package top.milkbox.sys.modular.role.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.milkbox.common.bo.EntityColumnExistence;
import top.milkbox.common.enums.CommonSortTypeEnum;
import top.milkbox.common.exceprion.CommonServiceException;
import top.milkbox.common.service.impl.CommonServiceImpl;
import top.milkbox.sys.modular.relationship.entity.SysRelationshipEntity;
import top.milkbox.sys.modular.relationship.enums.SysRelationshipTypeEnum;
import top.milkbox.sys.modular.relationship.service.SysRelationshipService;
import top.milkbox.sys.modular.role.entity.SysRoleEntity;
import top.milkbox.sys.modular.role.mapStruct.SysRoleMapStruct;
import top.milkbox.sys.modular.role.mapper.SysRoleMapper;
import top.milkbox.sys.modular.role.param.*;
import top.milkbox.sys.modular.role.service.SysRoleService;
import top.milkbox.sys.modular.role.vo.SysRoleVo;
import top.milkbox.common.utils.CommonUtil;
import top.milkbox.sys.modular.user.entity.SysUserEntity;
import top.milkbox.sys.modular.user.service.SysUserService;

import java.util.Collections;
import java.util.List;

/**
 * 系统_角色表（sys_role）服务层实现类
 *
 * @author milkbox
 * @date 2024-1-23
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysRoleServiceImpl extends CommonServiceImpl<SysRoleMapper, SysRoleEntity> implements SysRoleService {

    private SysRoleMapper sysRoleMapper;
    private SysRoleMapStruct sysRoleMapStruct;

    @Override
    public void add(SysRoleAddParam addParam) {
        SysRoleEntity entity = sysRoleMapStruct.addParamToEntity(addParam);
        super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<SysRoleIdParam> paramList) {
        // TODO 同时需要将关系表的角色信息删除
        super.removeByIds(paramList.stream().map(SysRoleIdParam::getId).toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(SysRoleEditParam editParam) {
        findEntity(editParam.getId());
        SysRoleEntity entity = sysRoleMapStruct.editParamToEntity(editParam);
        super.updateById(entity);
    }

    @Override
    public SysRoleVo detail(SysRoleIdParam idParam) {
        SysRoleEntity entity = findEntity(idParam.getId());
        SysRoleVo vo = sysRoleMapStruct.entityToVo(entity);
        // 此处进行数据翻译操作，，根据不同的业务逻辑将entity对象转为vo对象......

        return vo;
    }

    @Override
    public SysRoleEntity findEntity(Integer entityId) {
        SysRoleEntity entity = super.getById(entityId);
        if (ObjectUtil.isEmpty(entity)) {
            throw new CommonServiceException("实体未找到（{}）", entityId);
        }
        return entity;
    }

    @Override
    public Page<SysRoleVo> page(SysRolePageParam pageParam) {
        QueryWrapper<SysRoleEntity> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isAllNotEmpty(pageParam.getSortField(), pageParam.getSortType())) {
            queryWrapper.orderBy(true,
                    pageParam.getSortType() == CommonSortTypeEnum.ASC,
                    StrUtil.toUnderlineCase(pageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SysRoleEntity::getSortCode);
        }
        queryWrapper.lambda().orderByAsc(SysRoleEntity::getId);

        Page<SysRoleEntity> entityPage = super.page(pageParam.toBaomidouPage(), queryWrapper);
        // 此处进行远程调用或关联查询......

        Page<SysRoleVo> voPage = CommonUtil.convertPage(entityPage, entity -> {
            SysRoleVo vo = sysRoleMapStruct.entityToVo(entity);
            // 此处进行数据翻译操作，根据不同的业务逻辑将entity对象转为vo对象......

            return vo;
        });
        return voPage;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public EntityColumnExistence<Integer> reauthorizationUser(SysRoleAuthorizationUserParam reauthorizationUserParam) {
//        // 检查角色是否存在
//        findEntity(reauthorizationUserParam.getRoleId());
//        // 检查用户列表中的用户是否都存在
//        EntityColumnExistence<Integer> columnExistence = sysUserService.filterDoesNotExistColumn(
//                SysUserEntity::getId, reauthorizationUserParam.getUserIdList());
//        if (ObjectUtil.isEmpty(columnExistence.getExistColumnList())) {
//            throw new CommonServiceException("被授权的用户全部都不存在");
//        }
//        // 构造实体集合
//        List<SysRelationshipEntity> relationshipEntityList =
//                columnExistence.getExistColumnList().stream().map(userId -> {
//            SysRelationshipEntity relationshipEntity = new SysRelationshipEntity();
//            relationshipEntity.setObjectId(userId);
//            relationshipEntity.setTargetId(reauthorizationUserParam.getRoleId());
//            relationshipEntity.setCategory(SysRelationshipTypeEnum.SYS_USER_RELATE_SYS_ROLE);
//            return relationshipEntity;
//        }).toList();
//        // 删除此角色原来的授权信息
//        sysRelationshipService.deleteByTarget(Collections.singletonList(reauthorizationUserParam.getRoleId()));
//        // 保存实体集合
//        sysRelationshipService.saveBatch(relationshipEntityList);
//        return columnExistence;
//    }

}